import { ref, onMounted, onUnmounted, computed } from 'vue'

/**
 * 响应式断点
 */
export const BREAKPOINTS = {
  xs: 0,      // 超小屏幕（手机竖屏）
  sm: 576,    // 小屏幕（手机横屏）
  md: 768,    // 中等屏幕（平板竖屏）
  lg: 992,    // 大屏幕（平板横屏/小桌面）
  xl: 1200,   // 超大屏幕（桌面）
  xxl: 1600   // 超超大屏幕（大桌面）
}

/**
 * 设备类型
 */
export const DEVICE_TYPE = {
  MOBILE: 'mobile',     // 移动端
  TABLET: 'tablet',     // 平板
  DESKTOP: 'desktop'    // 桌面端
}

/**
 * 响应式工具 Hook
 */
export function useResponsive() {
  const windowWidth = ref(window.innerWidth)
  const windowHeight = ref(window.innerHeight)

  // 更新窗口尺寸
  const updateSize = () => {
    windowWidth.value = window.innerWidth
    windowHeight.value = window.innerHeight
  }

  // 防抖处理
  let resizeTimer = null
  const handleResize = () => {
    if (resizeTimer) clearTimeout(resizeTimer)
    resizeTimer = setTimeout(updateSize, 100)
  }

  onMounted(() => {
    window.addEventListener('resize', handleResize)
    updateSize()
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    if (resizeTimer) clearTimeout(resizeTimer)
  })

  // 判断是否为移动端
  const isMobile = computed(() => windowWidth.value < BREAKPOINTS.md)

  // 判断是否为平板
  const isTablet = computed(() => 
    windowWidth.value >= BREAKPOINTS.md && windowWidth.value < BREAKPOINTS.lg
  )

  // 判断是否为桌面端
  const isDesktop = computed(() => windowWidth.value >= BREAKPOINTS.lg)

  // 判断是否为小屏幕（手机）
  const isSmallScreen = computed(() => windowWidth.value < BREAKPOINTS.sm)

  // 判断是否为超小屏幕
  const isXSmall = computed(() => windowWidth.value < BREAKPOINTS.xs + 400)

  // 获取当前设备类型
  const deviceType = computed(() => {
    if (isMobile.value) return DEVICE_TYPE.MOBILE
    if (isTablet.value) return DEVICE_TYPE.TABLET
    return DEVICE_TYPE.DESKTOP
  })

  // 获取当前断点
  const currentBreakpoint = computed(() => {
    const width = windowWidth.value
    if (width < BREAKPOINTS.sm) return 'xs'
    if (width < BREAKPOINTS.md) return 'sm'
    if (width < BREAKPOINTS.lg) return 'md'
    if (width < BREAKPOINTS.xl) return 'lg'
    if (width < BREAKPOINTS.xxl) return 'xl'
    return 'xxl'
  })

  // 判断是否为横屏
  const isLandscape = computed(() => windowWidth.value > windowHeight.value)

  // 判断是否为竖屏
  const isPortrait = computed(() => windowWidth.value <= windowHeight.value)

  return {
    windowWidth,
    windowHeight,
    isMobile,
    isTablet,
    isDesktop,
    isSmallScreen,
    isXSmall,
    deviceType,
    currentBreakpoint,
    isLandscape,
    isPortrait
  }
}

/**
 * 获取响应式值
 * @param {Object} values - 不同断点的值 { mobile, tablet, desktop }
 * @returns {ComputedRef} 当前断点对应的值
 */
export function useResponsiveValue(values) {
  const { isMobile, isTablet } = useResponsive()

  return computed(() => {
    if (isMobile.value && values.mobile !== undefined) {
      return values.mobile
    }
    if (isTablet.value && values.tablet !== undefined) {
      return values.tablet
    }
    return values.desktop || values.default
  })
}

